package com.hnluchuan.staff.dao;

import java.util.ArrayList;
import java.util.Currency;
import java.util.List;
import java.util.Date;

import com.hnluchuan.staff.dto.UserDTO;
import com.hnluchuan.staff.model.User;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Repository;
import org.apache.commons.lang3.StringUtils;

import com.hnluchuan.core.dao.BaseDAO;
import com.hnluchuan.staff.model.Department;
import com.hnluchuan.staff.dto.DepartmentDTO;
import com.hnluchuan.core.support.Page;

@Repository
public class DepartmentDAO extends BaseDAO<Department> {

	public List<Department> find(DepartmentDTO dto, Page page) {
		StringBuilder hql = new StringBuilder();
		List<Object> paras = new ArrayList<Object>();
		hql.append("From Department n where 1 = 1 ");
		if (dto.getId() != null) {
			hql.append(" and n.id = ? ");
			paras.add(dto.getId());
		}
		if (StringUtils.isNotBlank(dto.getName())) {
			hql.append(" and n.name = ? ");
			paras.add(dto.getName());
		}
		hql.append(" order by n.id desc ");
		return super.find(hql.toString(), paras.toArray(), page);
	}

	public Department findOne(DepartmentDTO dto) {
		Page page = new Page();
		page.setPageSize(1);
		page.setPage(1);

		List<Department> list = this.find(dto, page);
		return CollectionUtils.isEmpty(list) ? null : list.get(0);
	}

	@Override
	public Long create(Department department) {
		if (department.getCreator() == null) {
			department.setCreator(department.getCreator());
		}
		if (department.getCreateTime() == null) {
			department.setCreateTime(new Date());
		}
		if (department.getUpdator() == null) {
			department.setUpdator(department.getUpdator());
		}
		if (department.getUpdateTime() == null) {
			department.setUpdateTime(new Date());
		}

	    /*
	    department.setId(456L);
	    User nuser=new User();
	    nuser.setId(1L);
		department.setCreator(nuser);
		department.setUpdator(nuser);
		*/
		return super.create(department);
	}

	@Override
	public void update(Department department) {
		if (department.getUpdator() == null) {
			//department.setUpdator(getCurrentUser());
		}
		if (department.getUpdateTime() == null) {
			department.setUpdateTime(new Date());
		}
		super.update(department);
	}

}
